package ltd.newbee.mall.config;

import com.corundumstudio.socketio.SocketIOServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @description:
 * @author: qzx
 * @date: 2022-08-12 20:09
 * @version: 1.0
 */
@Slf4j
@Component
public class SocketIOApplication implements CommandLineRunner {

    @Resource
    private SocketIOServer socketIOServer;

    @Override
    public void run(String... args) throws Exception {
        log.info("socket.io 启动成功");
        socketIOServer.startAsync();
    }

    @EventListener(value = {ContextClosedEvent.class, ContextStartedEvent.class})
    public void receiveEvents(ApplicationEvent event) {
        if (event instanceof ContextClosedEvent) {
            log.info("socket.io 关闭");
            socketIOServer.stop();
        } else if (event instanceof ContextStartedEvent) {
            log.info("== socket.io 先停止 ==");
            socketIOServer.stop();
            log.info("== socket.io 重新启动 ==");
            socketIOServer.startAsync();
        }
    }

}
